const Koa = require('koa');
const route = require('koa-route');
const fs = require('fs')

const app = new Koa();

// sessions
const session = require('koa-session')
app.keys = ['your-session-secret']
app.use(session({}, app))

// body parser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

// authentication
require('./auth')
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())


app.use(route.get("/default", (ctx) => {
  ctx.body = "default route";
}))


app.use(route.get("/", (ctx) => {
  ctx.body = "hello Koa default";
}))

app.use(route.get("/pleaselogin", (ctx) => {
  ctx.body = "please login"
}))

app.use(route.get("/login", (ctx) => {
  ctx.type = 'html'
  ctx.body = fs.createReadStream('views/login.html')
}))

app.use(route.get('/app', function (ctx) {
  if (ctx.isAuthenticated()) {
    ctx.type = 'html'
    ctx.body = fs.createReadStream('views/app.html')
  } else {
    ctx.redirect('/pleaselogin')
  }
}))

app.use(route.get("/whois", (ctx) => {
  if (ctx.isAuthenticated()) {
    var jsonFull = ctx.session.toJSON()
    var text = "User name " + jsonFull.passport.user + "\n"
    text = text + "json: \n" + JSON.stringify(jsonFull)
    ctx.body = text

  } else {
    ctx.redirect('/pleaselogin')
  }
}))

// app.use(route.get("/deser", passport.deserializeUser()))

// POST /login
// application/x-www-form-urlencoded
app.use(route.post('/login',
  passport.authenticate('local', {
    successRedirect: '/app',
    failureRedirect: '/'
  })
))




app.use(route.get('/hello', (ctx) => {
  ctx.type = 'application/json'
  ctx.body = { "info": "I am pusheen the cat." }
}))


app.use(route.get('/api/hello', (ctx) => {
  ctx.type = 'application/json'
  ctx.body = { "info": "This is api hello. I am pusheen the cat." }
}))


app.use(route.get('/logout'), (ctx) => {
  ctx.logout()
  ctx.redirect('/login')
})


app.listen(3000);